package com.fly.git.web;

import java.io.IOException;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fly.git.common.entity.JsonResult;
import com.fly.git.common.exception.ValidateException;
import com.fly.git.service.GitClientService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.Data;

@Api(tags = "api接口")
@RestController
public class IndexController
{
    @Autowired
    private GitClientService gitClient;
    
    @ApiOperation("设置运行时间")
    @PostMapping("configHours")
    public JsonResult<?> configHours(@Valid InputHour in)
    {
        gitClient.registerHours(in.getBeginHour(), in.getEndHour());
        return JsonResult.success(gitClient.getRunHours());
    }
    
    @ApiOperation("设置git参数")
    @PostMapping("init")
    public JsonResult<?> init(String username, String password, String email, String remoteGit)
    {
        if (StringUtils.isAnyBlank(username, password, email, remoteGit))
        {
            throw new ValidateException("参数值不能为空");
        }
        gitClient.setUserName(username);
        gitClient.setPassWord(password);
        gitClient.setEmail(email);
        gitClient.setRemoteGit(remoteGit);
        return JsonResult.success();
    }
    
    @ApiOperation("查询运行时间")
    @GetMapping("queryHours")
    public JsonResult<?> queryHours()
    {
        return JsonResult.success(gitClient.getRunHours());
    }
    
    @ApiOperation("测试远程提交")
    @PostMapping("remote-commit")
    public JsonResult<?> commit()
        throws IOException, GitAPIException
    {
        gitClient.runGitAll();
        return JsonResult.success();
    }
}

@Data
@ApiModel(description = "时间段数据对象")
class InputHour
{
    @NotNull(message = "开始时间不能为空")
    @Range(min = 0, max = 9, message = "开始时间必须在{min}-{max}之间")
    @ApiModelProperty(value = "开始时间", example = "8")
    private Integer beginHour;
    
    @NotNull(message = "结束时间不能为空")
    @Range(min = 12, max = 24, message = "结束时间必须在{min}-{max}之间")
    @ApiModelProperty(value = "结束时间", example = "24")
    private Integer endHour;
}
